package services

import (
	"errors"
	"fmt"
	"github.com/spf13/cast"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	string2 "longmen/server/pkg/common/helper/string"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

/*
func (s *Service) ChatRecord(r *api_models.ChatHistoryReq) error {
	var chatRecord models.ChatHistory
	chatRecord.RoomId = r.RoomId
	chatRecord.Uid = r.Uid
	chatRecord.Content = r.Content
	chatRecord.Id = r.Id
	chatRecord.CreateTime = timehelper.Now().Unix()
	err := cache.PushChatRecord(&chatRecord)
	return err
}
*/

// 聊天自增id
func GetChatMaxId() (*api_models.ChatMaxIdResp, error) {
	id := cache.GetChatAutoId()
	return &api_models.ChatMaxIdResp{Id: int(id)}, nil
}

// 写入聊天历史
func (s *Service) ChatHistory(req *api_models.ChatHistoryReq) error {
	r := &api_models.ChatHistoryReq{Id: req.Id, Uid: int(req.Uid), Content: req.Content, RoomId: int(req.RoomId)}

	err := s.ChatRecord(r)
	if err != nil {
		global.Log.Error(err)
	}
	return nil
}

// token验证
func (s *Service) UserTokenVerify(req *api_models.VerifyTokenReq) error {
	uid := req.Uid
	userToken, err := cache.GetUserToken(uid)
	if err != nil {
		return status.Errorf(codes.InvalidArgument, err.Error())
	}
	if userToken != req.Token {
		return status.Errorf(codes.InvalidArgument, "您已登陆超时")
	}
	return nil
}

// 礼物列表
func GetGiftListOld() (*api_models.GiftListResp, error) {
	rs, err := GetGiftList()
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, err.Error())
	}
	resp := new(api_models.GiftListResp)
	for _, v := range rs {
		resp.GiftList = append(resp.GiftList, &api_models.GiftList{
			Id:         uint32(v.Id),
			Title:      v.Title,
			Icon:       v.Icon,
			Animation:  v.Animation,
			AnimatType: uint32(v.AnimatType),
			Duration:   uint32(v.Duration),
			Price:      uint32(v.Price),
			Type:       uint32(v.Type),
			PriceType:  uint32(v.PriceType),
		})
	}
	return resp, nil
}

// 直播配置
func LiveConfig(req *api_models.LiveConfigReq) (*api_models.LiveConfigResp, error) {
	rs, err := GetLiveConfig(&api_models.LiveConfigReq{Anchorid: req.Anchorid})
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, err.Error())
	}

	return &api_models.LiveConfigResp{
		Liveid:         rs.Liveid,
		Heat:           rs.Heat,
		GiftFactor:     uint32(rs.Config.GiftFactor),
		Populaarsuse:   uint32(rs.Config.Populaarsuse),
		GiftTime:       uint32(rs.Config.GiftTime),
		SumbumistegurK: uint32(rs.Config.SumbumistegurK),
		Status:         rs.Status,
		Nickname:       rs.Nickname,
		Matchid:        rs.Matchid,
		OfficialType:   rs.OfficialType,
	}, nil
}

func AttentAnchor2(r *api_models.AttentanchorReq, user *models_main.User, ip string) (string, *api_models.AttentanchorResp, error) {
	fName := "AttentAnchor2"
	anchor, err := mysql.GetUserParam(map[string]interface{}{"id": r.Anchorid})
	if err != nil {
		return "主播账户状态异常", nil, fmt.Errorf("%s %s", util.Convert(fName), err.Error())
	}

	if anchor.Id <= 0 {
		return "主播账户状态异常", nil, errors.New("主播账户状态异常")
	}

	action_type := 0
	attent, err := db_main.GetAnchorFansParam(map[string]interface{}{"fansid": user.Id, "anchorid": r.Anchorid})
	if err != nil {
		return "", nil, fmt.Errorf("%s %s", util.Convert(fName), err.Error())
	}
	if attent.Id > 0 {
		//取消关注
		err = db_main.DeleteAnchorFans(attent)
		if err != nil {
			return "", nil, fmt.Errorf("%s %s", util.Convert(fName), err.Error())
		}
		//更新redis缓存
		attentids := cache.GetUserAttentAnchorIds(user.Id)
		if string2.IntIsInSlice(attentids, r.Anchorid) {
			attentids = util.DiffArrayInt(attentids, r.Anchorid)
		}
		cache.SetUserAttentAnchorIds(user.Id, attentids)

		fansCount, err := db_main.GetFansCount(map[string]interface{}{"anchorid": r.Anchorid})
		if err != nil {
			return "", nil, fmt.Errorf("%s %s", util.Convert(fName), err.Error())
		}
		cache.SetFansCount(r.Anchorid, fansCount)
		return "", &api_models.AttentanchorResp{FansCount: fansCount, Type: action_type}, nil
	} else {
		//直播中的主播入库时加上live_id
		liveInfo, _ := db_live.GetLiveParam(map[string]interface{}{"anchorid": r.Anchorid})

		attent = &models_main.AnchorFans{Fansid: user.Id, Anchorid: r.Anchorid, CreateTime: time.Now(), LiveId: liveInfo.Liveid}
		//关注
		err = db_main.InsertAnchorFans(attent)
		if err != nil {
			return "", nil, fmt.Errorf("%s %s", util.Convert(fName), err.Error())
		}
		//更新redis缓存
		attentids := cache.GetUserAttentAnchorIds(user.Id)
		if !string2.IntIsInSlice(attentids, r.Anchorid) {
			attentids = append(attentids, r.Anchorid)
		}
		cache.SetUserAttentAnchorIds(user.Id, attentids)

		fansCount, err := db_main.GetFansCount(map[string]interface{}{"anchorid": r.Anchorid})
		if err != nil {
			return "", nil, fmt.Errorf("%s %s", util.Convert(fName), err.Error())
		}
		cache.SetFansCount(r.Anchorid, fansCount)
		action_type = 1
		return "", &api_models.AttentanchorResp{FansCount: fansCount, Type: action_type}, nil
	}
}

// 屏蔽操作权限检测
func (s *Service) Permission(req *api_models.PermissionReq) (*api_models.PermissionResp, error) {
	if req.UserId != req.AnchorId {
		managerUser, err := db_live.GetLiveRoomManagerParam(map[string]interface{}{"mgrid": req.UserId})
		if err != nil {
			return &api_models.PermissionResp{Role: 1}, err
		}
		if managerUser.Id < 1 {
			return &api_models.PermissionResp{Role: 1}, errors.New("管理员ID不存在")
		}
		if managerUser.Anchorid != 0 && managerUser.Anchorid != int(req.AnchorId) { //不是超管和该房间管理
			return &api_models.PermissionResp{Role: 1}, errors.New("您没有当前房间的管理权限")
		}
	}

	if req.UserId == req.AnchorId {
		return &api_models.PermissionResp{Role: 2}, nil
	}

	return &api_models.PermissionResp{Role: 3}, nil
}

// 房间赛事
func AnchorMatchInfo(req *api_models.MatchSimpleDataReq) (*api_models.MatchSimpleDataResp, error) {
	resp, err := GetAnchorMatchInfo(&api_models.AttentanchorReq{Anchorid: int(req.Anchorid)})
	if err != nil {
		global.Log.Error("AnchorMatchInfo err : %err", err)
		return nil, status.Errorf(codes.InvalidArgument, err.Error())
	}
	return &api_models.MatchSimpleDataResp{HomeName: resp.HomeName, AwayName: resp.AwayName, Id: resp.Id, Time: resp.Time,
		KickoffTime: resp.KickoffTime, HomeId: resp.HomeId, AwayId: resp.AwayId, HomeScore: int32(resp.HomeScore),
		AwayScore: int32(resp.AwayScore), HomeLogo: resp.HomeLogo, AwayLogo: resp.AwayLogo, Status: resp.Status, CompetitionName: resp.CompetitionName}, nil
}

// 根据主播ID查找该主播正在直播的赛事简介(未启用)
func GetAnchorMatchInfo(r *api_models.AttentanchorReq) (*api_models.MatchSimpleDataResponse, error) {
	//fName := "GetAnchorMatchInfo"
	//liveInfo, err := repository.GetLiveParam(map[string]interface{}{"anchorid": r.Anchorid})
	//if err != nil {
	//	return nil, fmt.Errorf("%s %s", common.Convert(fName), err.Error())
	//}
	//if liveInfo.Matchid < 1 {
	//	return nil, fmt.Errorf("%s %s", common.Convert(fName), "主播未关联赛事")
	//}
	//resp, err := repository.GetHotMatchInfo(liveInfo)
	//if err != nil {
	//	return nil, fmt.Errorf("%s %s", common.Convert(fName), err)
	//}
	//confPub := cache.GetConfigPub()
	//if len(resp.AwayLogo) < 1 {
	//	resp.AwayLogo = confPub.DefaultMatchLogoUrl
	//}
	//if len(resp.HomeLogo) < 1 {
	//	resp.HomeLogo = confPub.DefaultMatchLogoUrl
	//}
	//if err != nil {
	//	return nil, fmt.Errorf("%s %s", common.Convert(fName), err)
	//}
	return &api_models.MatchSimpleDataResponse{}, nil
}

// 关注主播
func AttentAnchorOld(req *api_models.AttentanchorReq) (*api_models.AttentanchorResp, error) {
	user, _ := mysql.GetUserParam(map[string]interface{}{"id": req.Uid})
	if user.Id < 0 {
		global.Log.Error("user not exist ,uid : %v", req.Uid)
		return nil, status.Errorf(codes.InvalidArgument, "user not exist")
	}
	if user.Id == req.Anchorid {
		return nil, status.Errorf(codes.InvalidArgument, "不能关注自己")
	}
	//频繁操作限制：5秒内点击超过4次，冻结该用户1分钟，toast提示：【操作过于频繁请稍后再试】
	msg, err := util.CheckClickTime(user.Id, 4, time.Duration(5)*time.Second, time.Duration(1)*time.Minute)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "操作过于频繁请稍后再试")
	}
	msg, resp, err := AttentAnchor2(&api_models.AttentanchorReq{Anchorid: int(req.Anchorid)}, user, req.ClientIp)
	if err != nil {
		global.Log.Error("AttentAnchor err : %v,msg : %s", err, msg)
		return nil, status.Errorf(codes.InvalidArgument, err.Error())
	}
	return &api_models.AttentanchorResp{FansCount: resp.FansCount, Type: resp.Type}, nil
}

// 敏感词
func (s *Service) GetBlackKeywordOld() (*api_models.GetBlackKeywordResp, error) {
	//老聊天室不用，反空
	return &api_models.GetBlackKeywordResp{
		Keywords: []string{},
	}, nil
	keys, err := db_main.GetBlackKeyword()
	if err != nil {
		return nil, err
	}
	return &api_models.GetBlackKeywordResp{
		Keywords: keys,
	}, nil
}

// 主播合法检测
func AnchorCheck(req *api_models.LiveConfigReq) (*api_models.AnchorCheckResp, error) {
	anchorMap := cache.GetAnchorIds()
	if v, ok := anchorMap[cast.ToString(req.Anchorid)]; ok {
		return &api_models.AnchorCheckResp{Status: 1, AnchorType: cast.ToUint32(v)}, nil
	}
	return &api_models.AnchorCheckResp{Status: 1, AnchorType: cast.ToUint32(4)}, nil
	//return &pb.AnchorCheckResp{Status: 0}, nil
}

/*
// 背包

	func (s *Service) GetUserBackpack(req *pb.UserBackpackReq) (*pb.UserBackpackResp, error) {
		var userBackPack []*pb.UserBackpack
		list, err := repository.GetUserBackpacksParam(map[string]interface{}{"uid": req.GetUid(), "used": 0, "selected": 1}, "", 0, 0)
		if err != nil {
			return nil, err
		}
		tm := time.Now().Unix()
		for _, v := range list {
			flag := false
			for _, l := range userBackPack {
				if l.Gid == int32(v.Gid) && v.ExpTime >= tm && v.EffTime < tm {
					l.Num++
					flag = true
				}
			}
			if !flag {
				userBackPack = append(userBackPack, &pb.UserBackpack{Gid: int32(v.Gid), Num: 1, PropsType: int32(v.Type)})
			}
		}
		return &pb.UserBackpackResp{UserBackpack: userBackPack}, nil
	}
*/
func GetLiveConfig(r *api_models.LiveConfigReq) (*api_models.LiveConfigResp, error) {
	configPri := cache.GetConfigPri()
	resp := &api_models.LiveConfigResp{}
	resp.Config.SumbumistegurK = configPri.SumbumistegurK
	resp.Config.Populaarsuse = configPri.Populaarsuse
	resp.Config.GiftFactor = configPri.GiftFactor
	resp.Config.GiftTime = configPri.GiftTime

	anchorlive, err := cache.GetAnchorLive(r.Anchorid)
	if err != nil {
		return nil, err
	}
	if anchorlive != nil {
		resp.Liveid = anchorlive.Liveid
		//resp.Start = anchorlive.Start
		//resp.End = anchorlive.End
		resp.Matchid = anchorlive.Matchid
		resp.Status = uint8(anchorlive.Status)
		resp.Nickname = anchorlive.Nickname
		resp.Heat = anchorlive.Heat //基础执度
		return resp, nil
	}
	resp.Status = 1
	return resp, nil
}

func (s *Service) ChatRecord(r *api_models.ChatHistoryReq) error {
	var chatRecord models_main.ChatHistory
	chatRecord.RoomId = r.RoomId
	chatRecord.Uid = r.Uid
	chatRecord.Content = r.Content
	chatRecord.Id = r.Id
	chatRecord.CreateTime = time.Now().Unix()
	err := cache.PushChatRecord(&chatRecord)
	return err
}
